package com.coocaa.x.service.litewebserver.webserver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.coocaa.x.app.framework.app.LiteAppActivity;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litewebserver.webserver.aidl.ILiteWebServerService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.Hashtable;

public class WebServerActivity extends LiteAppActivity implements View.OnFocusChangeListener {

    private TextView currentNet = null;
    private LinearLayout pc = null;
    private LinearLayout mobile = null;
    private TextView webSite = null;
    private ImageView qrCode = null;
    private ViewFlipper flipper = null;
    private boolean isFirstFocus = true;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_layout);
        currentNet = (TextView) findViewById(R.id.webserver_net);
        pc = (LinearLayout) findViewById(R.id.webserver_pc_btn);
        mobile = (LinearLayout) findViewById(R.id.webserver_mobile_btn);
        webSite = (TextView) findViewById(R.id.webserver_website);
        qrCode = (ImageView) findViewById(R.id.webserver_qrcode);
        flipper = (ViewFlipper) findViewById(R.id.webserver_flipper);


        pc.setOnFocusChangeListener(this);
        mobile.setOnFocusChangeListener(this);
//        pc.getChildAt(0).setSelected(true);
//        pc.getChildAt(1).setSelected(true);
        mobile.getChildAt(0).setSelected(true);
        mobile.getChildAt(1).setSelected(true);
        flipper.setDisplayedChild(0);
        flipper.setOutAnimation(this, R.anim.alpha_1to0);
        flipper.setInAnimation(this, R.anim.alpha_0to1);

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
        updateNet();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (isFirstFocus) {
            isFirstFocus = false;
            return;
        }
        ViewGroup lastVg = null;
        if (hasFocus) {
            if (v.equals(mobile)) {
                flipper.showPrevious();
                lastVg = pc;
            } else if (v.equals(pc)) {
                flipper.showNext();
                lastVg = mobile;
            }
            ViewGroup vg = (ViewGroup) v;
            vg.getChildAt(0).setSelected(true);
            vg.getChildAt(1).setSelected(true);
            lastVg.getChildAt(0).setSelected(false);
            lastVg.getChildAt(1).setSelected(false);
        }
    }

    private void updateNet() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable() && info.isConnected()) {
            int type = info.getType(); // wifi==1
            if (type == 1) {
                WifiManager wifi_service = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifi_service.getConnectionInfo();
                currentNet.setText(String.format(getResources().getString(R.string.current_network), wifiInfo.getSSID()));
            } else {
                currentNet.setText(String.format(getResources().getString(R.string.current_network),
                        getResources().getString(R.string.ethernet)));
            }
            startServer();
        } else {
            currentNet.setText(String.format(getResources().getString(R.string.current_network),
                    getResources().getString(R.string.no_network)));
            webSite.setText(R.string.no_network);
            qrCode.setImageResource(R.drawable.webserver_qr_code_failed);
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                LogUtils.i("statusplugin", "sunny net action :" + action);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        updateNet();
                    }
                }, 2000);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    private void startServer() {
        new Thread(new Runnable() {
            private String ACTION = "com.coocaa.x.service.litewebserver";
            private ILiteWebServerService service = null;

            private ILiteWebServerService getService() {
                if (service == null || !service.asBinder().isBinderAlive()) {
                    IBinder binder = null;
                    while (binder == null) {
                        try {
                            XServiceManager.registerService(getPackageName(), ACTION);
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        binder = XServiceManager.getService(ACTION);
                    }
                    service = ILiteWebServerService.Stub.asInterface(binder);
                }
                return service;
            }

            private Bitmap createQRImage(String url) {
                try {
                    int QR_HEIGHT = 500;
                    int QR_WIDTH = 500;
                    //判断URL合法性
                    if (url == null || "".equals(url) || url.length() < 1) {
                        return null;
                    }
                    Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
                    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                    //图像数据转换，使用了矩阵转换
                    BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
                    int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
                    //下面这里按照二维码的算法，逐个生成二维码的图片，
                    //两个for循环是图片横列扫描的结果
//                    for (int y = 0; y < QR_HEIGHT; y++) {
//                        for (int x = 0; x < QR_WIDTH; x++) {
//                            if (bitMatrix.get(x, y)) {
//                                pixels[y * QR_WIDTH + x] = 0xff000000;
//                            } else {
//                                pixels[y * QR_WIDTH + x] = 0xffffffff;
//                            }
//                        }
//                    }
                    int[] rec = bitMatrix.getEnclosingRectangle();
                    int resWidth = rec[2] + 10;
                    int resHeight = rec[3] + 10;
                    BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
                    resMatrix.clear();
                    for (int i = 0; i < resWidth; i++) {
                        for (int j = 0; j < resHeight; j++) {
                            int w = i+rec[0]-5;
                            int h = j+rec[1]-5;
                            if (w>=0 && h>=0 && bitMatrix.get(w, h)) {
                               resMatrix.set(i, j);
                            }
                        }
                   }
                   int width = resMatrix.getWidth();
                   int height = resMatrix.getHeight();
                   for (int x = 0; x < width; x++) {
                       for (int y = 0; y < height; y++) {
                           if (resMatrix.get(x, y)) {
                                pixels[y * QR_WIDTH + x] = 0xff000000;
                           } else {
                                pixels[y * QR_WIDTH + x] = 0xffffffff;
                           }
                       }
                   }
                    //生成二维码图片的格式，使用ARGB_8888
                    Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
                    bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
                    return bitmap;
                } catch (WriterException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public void run() {
                try {
                    LogUtils.i("", "sunny hostname getService:" + getService().isStarted());
                    if (!getService().isStarted())
                        getService().start();
                    final String url = getService().getURL();
                    final Bitmap bitmap = createQRImage(url);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webSite.setText(url);
                            if (bitmap != null)
                                qrCode.setImageBitmap(bitmap);
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static final String APP_SESSION_KEY = "53bbb64256240b1b4c00b259";
    @Override
    protected String getAppSessionKey() {
        return APP_SESSION_KEY;
    }
}
